package com.vic.sb19.exception;

import com.vic.sb19.utils.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;

/**
 * @date 17/4/6
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController {


    /**
     * 单个文件的大小异常，对应配置：max-file-size
     * 一次性上传的总文件大小，对应配置：max-request-size
     *
     * 超过限制大小，都会抛出 MaxUploadSizeExceededException
     * @param maxUploadSizeExceededException
     * @param request
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(value = org.springframework.http.HttpStatus.OK)
    public String maxUploadSizeExceededException(MaxUploadSizeExceededException maxUploadSizeExceededException, HttpServletRequest request) {
        System.out.println("maxUploadSizeExceededException url:" + request.getRequestURI());
        return "总上传文件大小，不能超过" + ByteUtil.bytes2Mb(this.getPermittedSize(maxUploadSizeExceededException)).stripTrailingZeros().toPlainString() + "M";
    }

    private long getPermittedSize(MaxUploadSizeExceededException maxUploadSizeExceededEx) {
        // IllegalStateException
        Throwable originIllegalStateEx = maxUploadSizeExceededEx.getCause();

        if(originIllegalStateEx instanceof IllegalStateException) {
            IllegalStateException illegalStateEx = (IllegalStateException)originIllegalStateEx;
            Throwable originSizeLimitEx = illegalStateEx.getCause();

            // 单个文件超出
            if(originSizeLimitEx instanceof FileSizeLimitExceededException) {
                FileSizeLimitExceededException fileSizeLimitExceededEx = (FileSizeLimitExceededException)originSizeLimitEx;
                return fileSizeLimitExceededEx.getPermittedSize();
            }

            // 总的上传文件超出
            if(originSizeLimitEx instanceof SizeLimitExceededException) {
                SizeLimitExceededException sizeLimitExceededEx = (SizeLimitExceededException)originSizeLimitEx;
                return sizeLimitExceededEx.getPermittedSize();
            }
        }
        return 0L;
    }


}
